library(htmltools) ## HTML()
library(dplyr)
library(dtplyr)
library(data.table)
library(magrittr)
library(scales)
library(grattanCharts)  # devtools::install_github('hughparsonage/grattanCharts')
library(grattan)
library(rvest)
library(xml2)
library(httr)
library(leaflet)
library(ASGS)
Repayment_stress_by_SA2 <- 
  fread("~/Data/ABS/Mortgage-payment-stress.csv", na.strings = "--") %>% 
  .[`Mortgage monthly repayments` == "Households with mortgage repayments greater than 30% of household income"] %>% 
  setorderv("%") %>% 
  setnames("%", "Prop_geq_30pc") %>%
  .[SA2016_decoder, on = c("Suburb==SA2_NAME16")] %>%
  select(SA2_MAIN16, Prop_geq_30pc) %>%
  mutate(SA2_MAIN16 = factor(SA2_MAIN16))


SA2_2016_join <- SA2_2016
SA2_2016_join@data <-
  inner_join(SA2_2016_join@data, Repayment_stress_by_SA2, by = "SA2_MAIN16")
## Warning in inner_join_impl(x, y, by$x, by$y, suffix$x, suffix$y): joining
## factors with different levels, coercing to character vector
pal_v <- colorNumeric(palette = gpal(7, reverse = TRUE),
                      domain = NULL)
## I'm going off-piste: The Palette Of Nine is thine. May John have mercy on your soul.
SA2_2016_simple %>%
  leaflet %>%
  addPolygons(stroke = TRUE,
              opacity = 1,
              weight = 1,  # the border thickness / pixels
              color = "black",
              fillColor = ~pal_v(SA2_2016_join@data$Prop_geq_30pc), 
              fillOpacity = 1,
              label = lapply(paste0("<b>", 
                                    SA2_2016_join@data$SA2_NAME16, ":",
                                    "</b><br>",
                                    SA2_2016_join@data$Prop_geq_30pc,
                                    "%"),
                             HTML),
              highlightOptions = highlightOptions(weight = 2,
                                                  color = "white",
                                                  opacity = 1,
                                                  dashArray = "",
                                                  bringToFront = TRUE)) %>%
  addLegend(pal = pal_v, 
            opacity = 1,
            values = ~SA2_2016_join@data$Prop_geq_30pc,
            labFormat = labelFormat(suffix = "%"),
            title = "% households under mortgage stress")